<template>

  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <!--      选择角色-->
      <div class="title-container">
        <el-radio-group v-model="radio">
          <el-radio :label="1">学生</el-radio>
          <el-radio :label="2">老师</el-radio>
          <el-radio :label="3">管理员</el-radio>
        </el-radio-group>
      </div>
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="Password"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button :loading="loading" type="primary" style="width:75%;margin-bottom:30px;" @click.native.prevent="handleLogin">
        {{tips}}
      </el-button>
      <el-button type="primary" style="width:22%;margin-bottom:30px;" @click.native.prevent="change">
        忘记密码
      </el-button>
    </el-form>

    <!--    忘记密码内容-->
    <div class="update" v-if="isshow">
      <div class="update-content" style="padding-top: 0px">
        <el-button @click="close" type="info" icon="el-icon-close" circle style="position: relative;right: -812px"></el-button>
        <el-form :model="update" :rules="rules" ref="ruleForm"
                 label-width="100px" class="demo-ruleForm"
                 style="padding-top: 6%;padding-left: 30%">
          <el-form-item label="用户角色" prop="resource" style="width: 50%">
            <el-radio-group v-model="update.role">
              <el-radio label="student"></el-radio>
              <el-radio label="teacher"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="用户名" prop="name" style="width: 50%">
            <el-input v-model="update.id" style="color: #2d2f33"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="name" style="width: 50%">
            <el-input placeholder="请输入密码" v-model="update.pass" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="name" style="width: 50%">
            <el-input placeholder="请输入密码" v-model="update.ispass" show-password></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="name" style="width: 35%">
            <el-input v-model="update.yzm"></el-input>
          </el-form-item>
          <el-button type="primary" @click="ok">确认</el-button>
          <el-button @click="yzm">发送验证码</el-button>

        </el-form>

      </div>
    </div>
  </div>
</template>

<script>
  import { validUsername } from '@/utils/validate'
  // import SocialSign from './components/SocialSignin'
  import {getyzm, newpass} from '@/api/user'

  export default {
    name: 'Login',
    // components: { SocialSign },
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error('Please enter the correct user name'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('The password can not be less than 6 digits'))
        } else {
          callback()
        }
      }
      return {
        options: [{
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }, {
          value: '选项3',
          label: '蚵仔煎'
        }, {
          value: '选项4',
          label: '龙须面'
        }, {
          value: '选项5',
          label: '北京烤鸭'
        }],
        value: '',
        loginForm: {
          username: 'admin',
          password: '111111',
          //通过判断 radio的 1 2 3 给role赋值
          role: String
        },
        loginRules: {
          username: [{ required: true, trigger: 'blur', validator: validateUsername }],
          password: [{ required: true, trigger: 'blur', validator: validatePassword }]
        },
        passwordType: 'password',
        capsTooltip: false,
        loading: false,
        showDialog: false,
        redirect: undefined,
        otherQuery: {},
        //通过判断 radio的 1 2 3 给role赋值
        // 接收角色按钮的值  表示默认1是学生 2老师 3管理员
        radio: 1,
        //接收用户输入是否正确 以便提示输入
        tips: 'Login',
        //是否显示修改密码
        isshow: false,

        //忘记密码数据
        update: {
          role: '',
          id: '',
          pass: '',
          ispass: '',
          yzm: '',
        },
        rules: {
          id: [
            { required: true, message: '请输入用户名', trigger: 'change' }
          ],
          pass: [
            { type: 'date', required: true, message: '请输入新密码', trigger: 'change' }
          ],
          ispass: [
            { type: 'date', required: true, message: '确认密码', trigger: 'change' }
          ],
          yzm: [
            { type: 'array', required: true, message: '输入验证码', trigger: 'change' }
          ],
        }
      }
    },
    watch: {
      $route: {
        handler: function(route) {
          const query = route.query
          if (query) {
            this.redirect = query.redirect
            this.otherQuery = this.getOtherQuery(query)
          }
        },
        immediate: true
      }
    },
    created() {
      // window.addEventListener('storage', this.afterQRScan)
    },
    mounted() {
      if (this.loginForm.username === '') {
        this.$refs.username.focus()
      } else if (this.loginForm.password === '') {
        this.$refs.password.focus()
      }
    },
    destroyed() {
      // window.removeEventListener('storage', this.afterQRScan)
    },
    methods: {
      //预约提示变量 1搜索提示信息 2预约成功提示 3预约失败提示
      open(tips) {
        if (tips == 1) {
          this.$message('请 查 看 邮 箱 。')
        }else if (tips == 2) {
          this.$message.error('请填写正确的用户名和选定角色。')
        }else if(3) {
          this.$message({
            message: '密 码 修 改 成 功 。',
            type: 'success'
          });
        }else {
          this.$message({
            message: '密 码 修 改 失 败 。',
            type: 'warning'
          });
        }
      },
      //忘记密码 显示修改密码内容
      change() {
        this.isshow = true
      },
      //
      close() {
        this.isshow = false
        this.update = ''
      },
      //获取验证码
      yzm() {
        if(this.update.id && this.update.role){
          this.$message({message:'发送成功',type: 'success'})
          getyzm(this.update.id, this.update.role).then(res => {
            this.open(1)

            console.log(res,'打印发送验证码成功信息')
          }).catch(err => {
            this.open(2)
            console.log(err,'打印发送验证码失败信息')
          })
        }else {
          this.open(2)
        }

      },
      //确认修改密码
      ok() {
        if (this.update.yzm,this.update.id,this.update.role, this.update.pass){
          newpass(this.update.yzm,this.update.id,this.update.role, this.update.pass).then(res => {
            this.open(3)
            this.update = ''
            setTimeout( ()=> {
              this.isshow = false
            },1500)
            console.log(res,'打印修改密码成功信息')
          }).catch(err =>{
            this.open()
            console.log(err,'打印修改密码失败信息')
          })
        }else {
          this.open()
        }

      },
      checkCapslock(e) {
        const { key } = e
        this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        if (this.radio == 1){
          this.loginForm.role = 'student'
        }else if(this.radio == 2){
          this.loginForm.role = 'teacher'
        }else {
          this.loginForm.role = 'admin'
        }
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch('user/login', this.loginForm)
              .then(() => {
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
                this.loading = false
              })
              .catch(() => {
                this.loading = false
                this.tips = '请输入正确的用户名和密码'
                setTimeout(()=>{
                  this.tips = 'loading'
                },2000)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      getOtherQuery(query) {
        return Object.keys(query).reduce((acc, cur) => {
          if (cur !== 'redirect') {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
      }

    }
  }
</script>

<style lang="scss">

  .update {
    top: 50px;
    left: 0px;
    right: 0px;
    border-radius: 5px;
    margin-left:auto;
    margin-right:auto;
    width: 850px;
    height: 500px;
    position: fixed;
    background-color: rgb(45, 58, 75);
    z-index: 99999999999999;

    .update-content{
      width: 850px;
      height: 500px;
      border: 1px solid #CCCCCC;
      border-radius: 5px;
      background-color: rgb(45, 58, 75);
    }
  }
</style>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg:#283443;
  $light_gray:#fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }
    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }
</style>
